package com.freecloud.whispered.auth.oauth2;

import org.apache.commons.beanutils.ConvertUtils;
import org.apache.shiro.authz.ModularRealmAuthorizer;
import org.apache.shiro.realm.Realm;
import org.apache.shiro.subject.PrincipalCollection;

import java.util.Collection;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Set;

/**
 * 没有走对应doGetAuthorizationInfo授权方法，使用该类解决
 * @Author: maomao
 * @Date: 2019-08-14 00:02
 */
public class CustomModularRealmAuthorizer extends ModularRealmAuthorizer {

    @Override
    public boolean isPermitted(PrincipalCollection principals, String permission) {
        assertRealmsConfigured();
        // 所有Realm
        Collection<Realm> realms = getRealms();
        HashMap<String, Realm> realmHashMap = new HashMap<>(realms.size());
        for (Realm realm : realms) {
            if (realm.getName().contains("ClientOAuth2Realm")) {
                realmHashMap.put("ClientOAuth2Realm", realm);
            }else if (realm.getName().contains("OAuth2Realm")) {
                realmHashMap.put("OAuth2Realm", realm);
            }
        }

        Set<String> realmNames = principals.getRealmNames();
        if (realmNames != null) {
            String realmName = null;
            Iterator it = realmNames.iterator();
            while (it.hasNext()) {
                realmName = ConvertUtils.convert(it.next());
                if (realmName.contains("ClientOAuth2Realm")) {
                    return ((ClientOAuth2Realm) realmHashMap.get("ClientOAuth2Realm")).isPermitted(principals, permission);
                }else if (realmName.contains("OAuth2Realm")) {
                    return ((OAuth2Realm) realmHashMap.get("OAuth2Realm")).isPermitted(principals, permission);
                }
                break;
            }
        }
        return false;
    }

}
